package com.lwl.mini.executor;

/**
 * @author lwl
 * @create 2022/3/15 10:55
 */
public class ErrorContext {

    private static final ThreadLocal<ErrorContext> LOCAL = new ThreadLocal<ErrorContext>();
    /**
     * 表示换行，在Linux中 \n无法换行，而Java是跨平台
     */
    private static final String LINE_SEPARATOR = System.getProperty("line.separator","\n");


    private String message;
    private Throwable cause;
    private String resource;

    private ErrorContext(){
    }

    /**
     * 实例化
     * 单例模式
     * @returvn 单例对象ErrorContext
     */
    public static ErrorContext instance(){
        ErrorContext context = LOCAL.get();
        if(context == null) {
            context = new ErrorContext();
            LOCAL.set(context);
        }
        return context;
    }

    public ErrorContext message(String message){
        this.message = message;
        return this;
    }

    public ErrorContext cause(Throwable cause){
        this.cause = cause;
        return this;
    }
    public ErrorContext resource(String resource) {
        this.resource = resource;
        return this;
    }
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        if(this.message != null){
            sb.append(LINE_SEPARATOR).append("### ").append(this.message);
        }
        if(this.cause != null){
            sb.append(LINE_SEPARATOR).append("### Cause: ").append(cause.toString());
        }
        if(this.resource != null){
            sb.append(LINE_SEPARATOR).append("### The error may exist in").append(resource);
        }

        return sb.toString();
    }


}
